﻿using Bricks.Business.Data.Repositories.ScheduleManagement;
using Bricks.Business.Models.ScheduleManagement;
using Bricks.Component.Utils;
using Bricks.Site.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;

namespace Bricks.Business.Service.Impl
{
    /// <summary>
    /// 隧道统计服务实现
    /// </summary>
    [Export(typeof(ITunnelStatisticsService))]
    public class TunnelStatisticsService : ITunnelStatisticsService
    {
        [Import]
        protected ITunnelStatisticsRepository TunnelStatisticsRepository { get; set; }

        [Import]
        protected ITunnelStatisticsDetailRepository TunnelStatisticsDetailRepository { get; set; }

        public IQueryable<TunnelStatistics> TunnelStatisticses
        {
            get { return TunnelStatisticsRepository.Entities; }
        }

        public IQueryable<TunnelStatisticsDetail> TunnelStatisticsDetails
        {
            get { return TunnelStatisticsDetailRepository.Entities; }
        }

        /// <summary>
        /// 获取隧道统计列表
        /// </summary>
        /// <param name="projectID"></param>
        /// <param name="contractID"></param>
        /// <returns></returns>
        public List<TunnelStatisticsView> GetTunnelTotalList(Guid projectID, Guid contractID)
        {
            List<TunnelStatisticsView> result = new List<TunnelStatisticsView>();
            var dataList = TunnelStatisticses.Where(m => m.ProjectID == projectID && m.ContractID == contractID).OrderByDescending(m => m.AddDate);
            if (dataList != null && dataList.Count() > 0)
            {
                TunnelStatisticsView record;
                foreach (TunnelStatistics cs in dataList)
                {
                    record = new TunnelStatisticsView();
                    record.ID = cs.ID;
                    record.ProjectID = cs.ProjectID;
                    record.ContractID = cs.ContractID;
                    record.StatisticalCycle = cs.StatisticalCycle;

                    //明细过滤
                    var tunnelStatisticsDetails = from m in TunnelStatisticsDetails
                                                  where m.TunnelStatisticsID == cs.ID
                                                  select m;

                    if (tunnelStatisticsDetails != null && tunnelStatisticsDetails.Count() > 0)
                    {
                        //汇总各个字段
                        record.LengthDesignTotal = tunnelStatisticsDetails.Sum(m => m.LengthDesign);
                        record.LengthRealityTotal = tunnelStatisticsDetails.Sum(m => m.LengthReality);
                        record.HoleStoneProgressTotal = tunnelStatisticsDetails.Sum(m => m.HoleStoneProgress);
                        record.TunnelLiningProgressTotal = tunnelStatisticsDetails.Sum(m => m.TunnelLiningProgress);
                        record.TunnelExcavationProgressTotal = tunnelStatisticsDetails.Sum(m => m.TunnelExcavationProgress);
                        record.SecondaryLiningProgressTotal = tunnelStatisticsDetails.Sum(m => m.SecondaryLiningProgress);
                        record.DrainageDecorationProgressTotal = tunnelStatisticsDetails.Sum(m => m.DrainageDecorationProgress);

                        //因为可能为空，所以需要进行空判断后再计算
                        //实际
                        var lrt = record.LengthRealityTotal.HasValue ? record.LengthRealityTotal : 0;

                        //设计
                        var ldt = record.LengthDesignTotal.HasValue ? record.LengthDesignTotal : 0;

                        //总完成进度
                        decimal? countResult = 0;
                        if (ldt.HasValue && ldt.Value != 0)
                            countResult = (lrt / (ldt.Value));
                        if (countResult != null && countResult.HasValue)
                            record.TotalFinishedProgress = (countResult.Value * 100).ToString("F2") + "%";
                        else
                            record.TotalFinishedProgress = "0%";
                    }
                    result.Add(record);
                }
            }
            return result;
        }

        /// <summary>
        /// 获取隧道统计明细列表
        /// </summary>
        /// <param name="tunnelID">隧道ID</param>
        /// <param name="newTunnelID">新的隧道ID（拷贝上月数据时使用）</param>
        /// <returns></returns>
        public List<TunnelStatisticsDetailView> GetTunnelDetailList(Guid tunnelID, Guid newTunnelID)
        {
            List<TunnelStatisticsDetailView> result = new List<TunnelStatisticsDetailView>();
            var dataList = TunnelStatisticsDetails.Where(m => m.TunnelStatisticsID == tunnelID);
            if (dataList != null && dataList.Count() > 0)
            {
                TunnelStatisticsDetailView record;
                foreach (TunnelStatisticsDetail detail in dataList)
                {
                    record = new TunnelStatisticsDetailView();
                    record = detail.CopyTo<TunnelStatisticsDetailView>();
                    if (!newTunnelID.Equals(Guid.Empty))
                        record.TunnelStatisticsID = newTunnelID;

                    //因为可能为空，所以需要进行空判断后再计算
                    //实际
                    var lr = detail.LengthReality.HasValue ? detail.LengthReality : 0;

                    //设计
                    var ld = detail.LengthDesign.HasValue ? detail.LengthDesign : 0;

                    decimal? countResult = 0;
                    if (ld.HasValue && ld.Value != 0)
                        countResult = (lr / (ld.Value));
                    if (countResult != null && countResult.HasValue)
                        record.TotalFinishedProgress = (countResult.Value * 100).ToString("F2") + "%";
                    else
                        record.TotalFinishedProgress = "0%";

                    result.Add(record);
                }
            }
            return result;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="view"></param>
        /// <param name="details"></param>
        /// <returns></returns>
        public OperationResult Add(TunnelStatisticsView view)
        {
            var result = new OperationResult(OperationResultType.NoChanged);
            TunnelStatistics cs = new TunnelStatistics();
            cs = view.CopyTo<TunnelStatistics>();
            //保存隧道
            if (TunnelStatisticsRepository.Insert(cs) > 0)
            {
                //保存隧道明细
                string detailListJson = view.TunnelDetailListJson;
                if (!String.IsNullOrEmpty(detailListJson))
                {
                    List<TunnelStatisticsDetailView> detailViewList = JsonHelper.JsonDeserialize<List<TunnelStatisticsDetailView>>(detailListJson);
                    if (detailViewList != null && detailViewList.Count > 0)
                    {
                        List<TunnelStatisticsDetail> detailList = new List<TunnelStatisticsDetail>();
                        TunnelStatisticsDetail detail;
                        foreach (TunnelStatisticsDetailView item in detailViewList)
                        {
                            detail = new TunnelStatisticsDetail();
                            detail = item.CopyTo<TunnelStatisticsDetail>();
                            detail.ID = GuidHelper.NewGuid();
                            detailList.Add(detail);
                        }
                        if (detailList.Count > 0)
                        {
                            if (TunnelStatisticsDetailRepository.Insert(detailList) > 0)
                            {
                                result = new OperationResult(OperationResultType.Success, "保存记录和明细成功");
                            }
                        }
                    }
                }
                result = new OperationResult(OperationResultType.Success, "保存记录成功");
            }
            return result;
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="view"></param>
        /// <param name="details"></param>
        /// <returns></returns>
        public OperationResult Modify(TunnelStatisticsView view)
        {
            var result = new OperationResult(OperationResultType.NoChanged);
            TunnelStatistics cs = new TunnelStatistics();
            cs = view.CopyTo<TunnelStatistics>();
            //保存隧道
            if (TunnelStatisticsRepository.Update(cs) >= 0)
            {
                //删除旧的隧道明细
                var oldDetailList = TunnelStatisticsDetails.Where(m => m.TunnelStatisticsID == cs.ID);
                if (oldDetailList != null && oldDetailList.Count() > 0)
                {
                    TunnelStatisticsDetailRepository.Delete(oldDetailList);
                }

                //保存隧道明细
                string detailListJson = view.TunnelDetailListJson;
                if (!String.IsNullOrEmpty(detailListJson))
                {
                    //json->对象（注：使用此方法，当为空时，可能转换出错）
                    List<TunnelStatisticsDetailView> detailViewList = JsonHelper.JsonDeserialize<List<TunnelStatisticsDetailView>>(detailListJson);
                    if (detailViewList != null && detailViewList.Count > 0)
                    {
                        List<TunnelStatisticsDetail> detailList = new List<TunnelStatisticsDetail>();
                        TunnelStatisticsDetail detail;
                        foreach (TunnelStatisticsDetailView item in detailViewList)
                        {
                            detail = new TunnelStatisticsDetail();
                            detail = item.CopyTo<TunnelStatisticsDetail>();
                            detailList.Add(detail);
                        }
                        if (detailList.Count > 0)
                        {
                            if (TunnelStatisticsDetailRepository.Insert(detailList) > 0)
                            {
                                result = new OperationResult(OperationResultType.Success, "保存记录和明细成功");
                            }
                        }
                    }
                }
                result = new OperationResult(OperationResultType.Success, "保存记录和明细成功");
            }
            return result;
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="tunnelStatisticsView"></param>
        /// <param name="saveList"></param>
        /// <param name="isUpdateDetails"></param>
        public void Save(TunnelStatisticsView tunnelStatisticsView, List<TunnelStatisticsDetailView> saveList, bool isUpdateDetails = true)
        {
            TunnelStatistics record = TunnelStatisticsRepository.Entities.FirstOrDefault(a => a.ID == tunnelStatisticsView.ID);
            if (record != null)
            {
                Modify(tunnelStatisticsView);
            }
            else
            {
                Add(tunnelStatisticsView);
            }

            if (isUpdateDetails)
            {
                DeleteTunnelStatisticsDetails(tunnelStatisticsView.ID);
                foreach (TunnelStatisticsDetailView bsd in saveList)
                {
                    InsertTunnelStatisticsDetail(bsd);
                }
            }
        }

        /// <summary>
        /// 清空隧道对应的明细记录
        /// </summary>
        /// <param name="tunnelStatisticsID"></param>
        private void DeleteTunnelStatisticsDetails(Guid tunnelStatisticsID)
        {
            List<TunnelStatisticsDetail> lstTunnelStatisticsDetails = TunnelStatisticsDetailRepository.Entities.Where(a => a.TunnelStatisticsID == tunnelStatisticsID).ToList();
            foreach (TunnelStatisticsDetail bsd in lstTunnelStatisticsDetails)
            {
                TunnelStatisticsDetailRepository.Delete(bsd.ID);
            }
        }

        /// <summary>
        /// 插入隧道明细记录
        /// </summary>
        /// <param name="tunnelStatisticsDetailView"></param>
        private void InsertTunnelStatisticsDetail(TunnelStatisticsDetailView tunnelStatisticsDetailView)
        {
            TunnelStatisticsDetail record = new TunnelStatisticsDetail();
            record = tunnelStatisticsDetailView.CopyTo<TunnelStatisticsDetail>();
            TunnelStatisticsDetailRepository.Insert(record);
        }

        /// <summary>
        /// 获取隧道信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public TunnelStatisticsView GetTunnel(Guid id)
        {
            TunnelStatisticsView result = new TunnelStatisticsView();
            var tunnel = TunnelStatisticses.FirstOrDefault(m => m.ID == id);
            if (tunnel != null)
            {
                result = tunnel.CopyTo<TunnelStatisticsView>();
            }
            return result;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public OperationResult Delete(Guid id)
        {
            var result = new OperationResult(OperationResultType.NoChanged);
            if (id != null && !id.Equals(Guid.Empty))
            {
                try
                {
                    //查找子记录并删除
                    var detailList = TunnelStatisticsDetails.Where(m => m.TunnelStatisticsID == id);
                    if (detailList != null && detailList.Count() > 0)
                    {
                        TunnelStatisticsDetailRepository.Delete(detailList);
                    }

                    //查找主记录并删除
                    var tunnel = TunnelStatisticses.FirstOrDefault(m => m.ID == id);
                    if (tunnel != null)
                    {
                        if (TunnelStatisticsRepository.Delete(tunnel) > 0)
                        {
                            result = new OperationResult(OperationResultType.Success, "删除成功");
                        }
                    }
                }
                catch (Exception ex)
                {
                    result = new OperationResult(OperationResultType.Error, ex.Message);
                }
            }
            return result;
        }
    }
}
